<template>
  <div class="common-layout" id='imgtxtrpt' :class='IsEmpty(labMainInfoObj.id)?"no-edit":""'>

    <div class="tableBody">
      <Splitpanes>
        <!-- 左侧表格  -->
        <Pane size="65">
          <!--@cell-dblclick="tatItemRowClick"   双击移除-->
<!--          :footer-method="footerMethod" :show-footer="true"-->
          <vxe-table ref="tatItemTableRef" :span-method="mergeRowMethod"
                     :data="tableFields"
                     :loading="iloading"
                     class="mytable-scrollbar supplierTableClazz"
                     border align="center"
                     height="100%"
                     :row-config="{ isCurrent: true, isHover: true }"
                     :column-config="{ resizable: true }"
                     :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }"
                     resizable show-overflow keep-source>

            <vxe-colgroup title="细胞名称"   header-class-name="custom-span">
              <vxe-column field="detailGroup" title="" width="80"
                          header-class-name="custom-hid" >

              </vxe-column>
              <vxe-column field="detailGroup2" title="" min-width="50"
                          header-class-name="custom-hid"></vxe-column>
              <vxe-column field="tempItemNa" title="" min-width="80">
                <template #default="{ row }">
                  <span v-if='!IsEmpty(row.detailGroup2)&&!IsEmpty(row.detailGroup)'>
                    {{ row.tempItemNa }}
                  </span>
                  <span v-else-if='IsEmpty(row.detailGroup2)&&!IsEmpty(row.detailGroup)' class="custom-span-left">
                    {{ row.tempItemNa }}
                  </span>
                  <span v-else class="custom-span-left3">
                      {{ row.tempItemNa }}
                    </span>
                </template>
              </vxe-column>
            </vxe-colgroup>
            <vxe-colgroup title="血片">
              <vxe-column field="testResult" title="（%）" :edit-render="{}">
                <template #edit="{ row }">
                  <el-input v-model="row.testResult" v-if='row.isCalcItem === 1'
                            @blur="onSubmitTxt(row,'testResult')"
                            :disabled="resultIsDisabled()"
                  ></el-input>
                  <el-input-number v-model="row.testResult" v-else
                             @blur="onSubmit(row,'testResult')"
                             :disabled="resultIsDisabled()"
                             :precision="2" :step="0.01"
                             size="small"
                             controls-position="right"
                  ></el-input-number>
                </template>
              </vxe-column>
            </vxe-colgroup>

            <vxe-colgroup title="髓片">
              <vxe-column field="ref" title="平均值" width="50">
                <template #default="{ row }">
                  <span v-if='!IsEmpty(row.defValue3)'>
                    {{ row.ref }}
                  </span>
                  <span v-else class="custom-span-right">
                    {{ row.ref }}
                  </span>
                </template>
              </vxe-column>
              <vxe-column field="defValue3" title="标准差" width="50"></vxe-column>
              <vxe-column field="resultDesc" title="（%）" :edit-render="{}">
                <template #edit="{ row }">
                  <el-input v-model="row.resultDesc" v-if='row.isCalcItem === 1'
                            @blur="onSubmitTxt(row,'resultDesc')"
                            :disabled="resultIsDisabled()"
                  ></el-input>
                  <el-input-number v-model="row.resultDesc" v-else
                                    @blur="onSubmit(row,'resultDesc')"
                                    :disabled="resultIsDisabled()"
                                   :precision="2" :step="0.01"
                                   size="small"
                                   controls-position="right"
                  ></el-input-number>
                </template>
              </vxe-column>
            </vxe-colgroup>

          </vxe-table>
        </Pane>
        <Pane size="35">
          <el-row v-for="(item) in itemFields" :key="item.id">
            <el-col :span="24">
              <el-form-item :label="item.tempItemNa+'：'" label-width='100px'>
                <vxe-textarea v-model="item.resultDesc" :placeholder="'请输入'+item.tempItemNa"
                              v-if="(item.typeFlag == '3' && !IsEmpty(item.typeCode))"
                              :rows='IsEmpty(item.textHeight)?item.textHeight:1' @focusout="onSubmitArea(item)"
                              :class='item.tempItemNo'
                              @focus="showTypeCodeDrawer(item)"
                              :disabled="resultIsDisabled()"></vxe-textarea>
                <vxe-textarea v-if="!(item.typeFlag == '3' && !IsEmpty(item.typeCode))"
                              v-model="item.resultDesc" :placeholder="'请输入'+item.tempItemNa"
                              :rows='IsEmpty(item.textHeight)?item.textHeight:1'
                              @focusout="onSubmitArea(item)"
                              :disabled="resultIsDisabled()"></vxe-textarea>
              </el-form-item>
            </el-col>
          </el-row>
        </Pane>
      </Splitpanes>
    </div>
    <FormEditDrawer ref="diagnosTempDrawerRef" @sltDiagnosTempInfo="selectDiagnosTempInfo">
    </FormEditDrawer>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import { ref, reactive, watch, getCurrentInstance, PropType, onMounted, inject, defineEmits,defineExpose } from 'vue';
import { IsEmpty, formatDateTime } from '@/utils/common'; //导入工具函数
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import SelectDataGrid from '@/components/SelectDataGrid.vue';
import FormTextArea from '../img_txt_rpt/FormTextArea.vue';
import FormEditDrawer from '../img_txt_rpt/FormEditDrawer.vue';
import { AppStore } from '@/stores/store';
import { FormInstance, ComponentSize } from 'element-plus';
import DiagnosTempDrawer from '@/components/DiagnosTempDrawer.vue';
import { Splitpanes, Pane } from 'splitpanes';

let labMainInfoObj: any = reactive({}); /**检验记录当前选中对象 */
import type { VxeTablePropTypes } from 'vxe-table';
import request from '@/api';
// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
const apiPath = ref((window as any).apiUrl.VITE_SERVER_URL);
let store = AppStore();
let orgId = ref(null);
let iloading = ref(false);
let diagnosTempDrawerRef = ref(null);

//fixme:需要考虑这里还要不要留
const rptImages = inject('rptImages');
const size = ref<ComponentSize>('large');

const fields = reactive([]);
const tableFields = reactive([]);
const itemFields = reactive([]);
const calcItems = reactive({ });//需要计算的项
const calcFormulas = reactive({ });//计算公式
//共享Maininfo
const rptMaininfo = inject('rptMaininfo');

let templateId = ref(null);

defineExpose({
  onSubmit,
  initPage,
  reviewValidateVsCountIsEqual
});

const proxyEmit = defineEmits(['updateTestList']);
// 父组件传值
let props = defineProps({
  currentRow: { type: Object as PropType<any>, required: true }
}) as any;

onMounted(() => {
  orgId = store.userInfo.orgId;
});

// 方法定义区 =============

function loadItem(item) {
  item.rptGroup = labMainInfoObj.rptGroup;
  item.instrCode = labMainInfoObj.rptGroup;
  item.instrNa = labMainInfoObj.rptGroupNa;
  item.rptGroupName = labMainInfoObj.rptGroupNa;
  item.isNeedToReport = 1;
  item.itemNo = item.tempItemNo;
  item.itemNa = item.tempItemNa;
  item.sampleNo = labMainInfoObj.sampleNo;
  item.sampleda = labMainInfoObj.sampleda;
  item.reqNo = labMainInfoObj.reqNo;
  item.maininfoId = labMainInfoObj.id;
  return item;
}
// 保存非计算结果信息
function onSubmitTxt(item: any, filedf) {
  if (!IsEmpty(item[filedf])) {
    item=loadItem(item);
    submitForm(item);
  }
}

// 保存计算结果信息
function onSubmit(item: any, filedf) {
  if (!IsEmpty(item[filedf])) {
    let items=calcItemValue(item);
    item=loadItem(item);
    if(IsEmpty(items)){
      items.length=0
    }
    items.push(item);
    submitFormBatch(items);
  }
}

function onSubmitArea(item: any) {
  if (!IsEmpty(item.resultDesc)) {
    item.rptGroup = labMainInfoObj.rptGroup;
    item.instrCode = labMainInfoObj.rptGroup;
    item.instrNa = labMainInfoObj.rptGroupNa;
    item.rptGroupName = labMainInfoObj.rptGroupNa;
    item.isNeedToReport = 1;
    item.itemNo = item.tempItemNo;
    item.itemNa = item.tempItemNa;
    item.sampleNo = labMainInfoObj.sampleNo;
    item.sampleda = labMainInfoObj.sampleda;
    item.rptResult = item.resultDesc?.slice(0, 255); //截取前249个字符
    item.reqNo = labMainInfoObj.reqNo;
    item.maininfoId = labMainInfoObj.id;
    submitFormArea(item);
  }
}

// 保存
const submitFormArea = (item: any) => {
  const url = '/lab/rptResult/saveImgTxtRptValue';
  proxy.$http
    //注意此处的数据条数
    .post(url, item)
    .then((res: any) => {
      if (res.status.code === 1) {
        if (IsEmpty(labMainInfoObj.id)) {
          //proxy.$emit
          labMainInfoObj.id=res.data.maininfoId;
          proxyEmit('updateTestList', { isSelCurRow: true, isRefreshRptResult: false, mainInfoId: res.data.maininfoId });
        }
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
    });
};
// 保存
const submitForm = (item: any) => {
  iloading.value=true;
  const url = '/lab/rptResult/saveImgTxtRptValue';
  proxy.$http
    //注意此处的数据条数
    .post(url, item)
    .then((res: any) => {
      if (res.status.code === 1) {
        if (IsEmpty(labMainInfoObj.id)) {
          //proxy.$emit
          labMainInfoObj.id=res.data.maininfoId;
          proxyEmit('updateTestList', { isSelCurRow: true, isRefreshRptResult: false, mainInfoId: res.data.maininfoId });
          //findTemplateItemList();
        }
        iloading.value=false;
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
    });
};
// 批量保存
const submitFormBatch = (items: any) => {
  const url = '/lab/rptResult/saveImgTxtRptValueBatch';
  proxy.$http
    //注意此处的数据条数
    .post(url, items)
    .then((res: any) => {
      if (res.status.code === 1) {
        if (IsEmpty(labMainInfoObj.id)) {
          //proxy.$emit
          labMainInfoObj.id=res.data.maininfoId;
          proxyEmit('updateTestList', { isSelCurRow: true, isRefreshRptResult: false, mainInfoId: res.data.maininfoId });
          //findTemplateItemList();
        }
        iloading.value=false;
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
    });
};
function initPage(mainInfoRow: any) {
  Object.assign(labMainInfoObj, mainInfoRow);
  findTemplateItemList();
}
// 获取最右侧 项目设定表格数据
function findTemplateItemList() {
  iloading.value = true;
  fields.length = 0; //放入数据前清空数据
  const url = '/lab/rptResult/findRptResultItemByTemp';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        templateId: templateId.value,
        // sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
        sampleDaStr: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd'),
        rptGroup: labMainInfoObj.rptGroup,
        sampleNo: labMainInfoObj.sampleNo,
        reqNo: labMainInfoObj.reqNo,
        mainInfoId: labMainInfoObj.id
      }
    })
    .then((res: any) => {
      fields.length = 0; //放入数据前清空数据
      fields.push(...res.data);
      populateCalcItems();
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
      VxeMessage('获取图报告单项目异常', VxeNotifyType.error);
    });
}
//根据类型分不同变量数据
function populateCalcItems() {
  tableFields.length=0;
  itemFields.length=0;
  calcItems.length=0;
  fields.forEach(field => {
    if (field.typeFlag=='1') {
      tableFields.push(field);
      if (field.isCalcItem === 1) {
        calcItems[field.tempItemNo] =field;
        let arrs= field.calcItemFormula.split(':');
        let arrItems=[];
        arrs.forEach(item => {
          let itemObj= {
            calcFormula: item,
            testResult:0.00,
            resultDesc:0.00
          };
          arrItems.push(itemObj);
        });
        calcFormulas[field.tempItemNo] =arrItems;
      }
    }else{
      itemFields.push(field);
    }
  });
}
//计算值返回需要计算的项
function calcItemValue(item: any) {
  if (!IsEmpty(calcItems[item.tempItemNo])) {
    return null;
  }
  const keys = Object.keys(calcFormulas);
  for (const key of keys) {
    calcFormulas[key].forEach(itemk=>{
      itemk.testResult=0.00;
      itemk.resultDesc=0.00;
    });
  }
  tableFields.forEach(field => {
    if (IsEmpty(calcItems[field.tempItemNo])) {
      //跳出当前循环，避免重复计算
      for (const key of keys) {
        calcFormulas[key].forEach(itemj=>{
          if(itemj.calcFormula.indexOf(`[${field.tempItemNo}]`)>-1){
            itemj.testResult=floatAdd(itemj.testResult,reFloat(field.testResult));
            itemj.resultDesc=floatAdd(itemj.resultDesc,reFloat(field.resultDesc));
          }
        });
      }
    }
  });
  let updataItem = [];
  tableFields.forEach(field => {
    if (!IsEmpty(calcItems[field.tempItemNo])) {
      const key =field.tempItemNo;
      if(calcFormulas[key].length==1){
        field.testResult=calcFormulas[key][0].testResult>0.00?calcFormulas[key][0].testResult:'';
        field.resultDesc=calcFormulas[key][0].resultDesc>0.00?calcFormulas[key][0].resultDesc:'';
      }
      if(calcFormulas[key].length==2) {
        if(calcFormulas[key][0].testResult!=0||calcFormulas[key][1].testResult!=0){
          field.testResult=calcFormulas[key][0].testResult+":"+calcFormulas[key][1].testResult;
        }
        if(calcFormulas[key][0].resultDesc!=0||calcFormulas[key][1].resultDesc!=0){
          field.resultDesc=calcFormulas[key][0].resultDesc+":"+calcFormulas[key][1].resultDesc;
        }
      }
      field=loadItem(field);
      updataItem.push(field);
    }
  });
  return updataItem;
}
//转为浮点数
function reFloat(val) {
  const fval = parseFloat(val,2);
  if (isNaN(fval)) {
    return 0;
  } else {
    return fval;
  }
}
//浮点数加法函数
function floatAdd(a, b) {
  const factor = Math.pow(10, Math.max(
    (a.toString().split('.')[1] || '').length,
    (b.toString().split('.')[1] || '').length
  ));
  return (Math.round(a * factor) + Math.round(b * factor)) / factor;
}

function showTypeCodeDrawer(item) {
  showDiagnosTempDrawer(item);
}

function showDiagnosTempDrawer(item) {
  diagnosTempDrawerRef.value.initPage(item);
}
function selectDiagnosTempInfo(row) {
  onSubmitArea(row);
}

function resultIsDisabled() {
  if (!IsEmpty(labMainInfoObj) && labMainInfoObj.isChk == '2') {
    return true;
  } else {
    return false;
  }
}
/**审核验证，项目对照，检验结果数量是否相等 */
async function reviewValidateVsCountIsEqual() {
  let res = false;
  try {
    res = false;
  } catch (error) {}
  return res;
}

function mergeRowMethod({ row, _rowIndex, column, visibleData }) {
  const fields = ['detailGroup', 'detailGroup2', 'tempItemNa'];
  const cellValue = row[column.field];
  if (cellValue && fields.includes(column.field)) {
    const prevRow = visibleData[_rowIndex - 1];
    let nextRow = visibleData[_rowIndex + 1];
    if (prevRow && prevRow[column.field] === cellValue) {
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (nextRow && nextRow[column.field] === cellValue) {
        nextRow = visibleData[++countRowspan + _rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-input__wrapper){
  padding-left: 0px !important;
  padding-right: 0px !important;
}
:deep(.el-input-number--small){
  width: 60px !important;
}
:deep(.el-input__wrapper){
  width: 20px !important;
}
:deep(.el-input-number){
  text-align: right;
}
:deep(.el-input-number__increase){
  display: none;
}
:deep(.el-input-number__decrease){
  display: none;
}
:deep(.vxe-header--row){
  height: 35px !important;
  padding:0 !important;
}
// 表格单元格高度
:deep(.vxe-body--column){
  height: 35px !important;
}
:deep(.custom-hid){
  background-image: linear-gradient(#f4f6fb, #f4f6fb), linear-gradient(#f4f6fb, #f4f6fb) !important;
}
:deep(.custom-span .vxe-cell .vxe-cell--title){
  width: 99% !important;
  position: absolute !important;
  background-color: rgb(244, 246, 251) !important;
  bottom: -15px !important;
  left: 0 !important;
  z-index: 99999;
}
.custom-span-left{
  width: 99% !important;
  position: absolute !important;
  background-color: #ffffff !important;
  left: -5em !important;
  bottom: 1px !important;
  height:96% !important;
  line-height: 2.9em;
  z-index: 99999;
}
.custom-span-left3{
  width: 180% !important;
  position: absolute !important;
  background-color: #ffffff !important;
  left: -16em !important;
  bottom: 1px !important;
  height:96% !important;
  line-height: 2.9em;
  z-index: 99999;
}
.custom-span-right{
  width: 99% !important;
  position: absolute !important;
  background-color: #ffffff !important;
  right: -2em !important;
  bottom: 1px !important;
  height:96% !important;
  line-height: 2.9em;
  z-index: 99999;
}
.custom-span-group{
  //将文字向下展示
  writing-mode: vertical-rl;
  display: inline-block; /* 确保 span 元素可以应用 writing-mode */
  position: absolute !important;
  left: 0 !important;
}
#imgtxtrpt {
  height: calc(94vh - 10px);
  padding: 21px;
  overflow: auto;
  .tableBody {
    height: calc(100% - 100px);
  }
  // 中等尺寸时 配置扩展属性按钮
  .el-button--default {
    padding: 5px 11px;
  }
  table {
    border-collapse: collapse; /* 确保表格边框合并为单一边框 */
  }

  table,
  th,
  td {
    border: 1px solid black; /* 设置表格、表头、单元格的边框 */
    text-align: center;
  }
  .imgArea {
    margin-top: 4px;
    font-size: 14px;
    p {
      text-align: center;
      img {
        width: 40%;
        padding: 5px;
      }
    }
    .textArea {
      min-height: 30px;
    }
  }

  .font14 {
    font-size: 14px;
  }
}
#imgtxtrpt::-webkit-scrollbar {
  display: none;
}
.no-edit {
  user-select: none; /* 禁止选择文本 */
  pointer-events: none; /* 禁止所有鼠标事件 */
  cursor: not-allowed; /* 改变鼠标指针样式为禁止符号 */
  //cursor:none;
  opacity: 0.7;
}
</style>

